package com.epfresh.fragment;


import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.epfresh.R;
import com.epfresh.activity.CommonStoreActivity;
import com.epfresh.activity.DcStoreActivity;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.api.entity.*;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.utils.AppUtils;
import com.epfresh.api.utils.IntenetUtil;
import com.epfresh.api.web.AgentWeb;
import com.epfresh.api.web.ChromeClientCallbackManager;
import com.epfresh.api.web.WebDefaultSettingsManager;
import com.epfresh.api.web.WebSettings;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;
import java.util.Map;


public class StoreHomeWebFragment extends Fragment implements FragmentKeyDown {
    private PtrFrameLayout ptrFrameLayout;
    WebView webView;
    PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {

            if (webView != null){

                return PtrDefaultHandler.checkContentCanBePulledDown(frame, webView, header);
            }
            return false;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {

            if (webView != null){
                webView.loadUrl(getUrl());
            }else {
            }
            ptrFrameLayout.refreshComplete();

        }
    };

//    private ImageView mBackImageView;
//    private View mLineView;
//    private ImageView mFinishImageView;
//    private TextView mTitleTextView;
    protected AgentWeb mAgentWeb;
    public static final String URL_KEY="url_key";

    public static StoreHomeWebFragment getInstance(Bundle bundle) {

        StoreHomeWebFragment mAgentWebFragment = new StoreHomeWebFragment();
        if (bundle != null)
            mAgentWebFragment.setArguments(bundle);

        return mAgentWebFragment;

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(com.epfresh.R.layout.fragment_dc_home, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.e("just begin","storeHomeFragment");
        View vGroup = view.findViewById(R.id.v_group);

        ptrFrameLayout = (PtrFrameLayout) view.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent((ViewGroup) vGroup, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))//
                .setIndicatorColorWithHeight(-1,2)//
                .setWebSettings(getSettings())//
                .setWebViewClient(mWebViewClient)
                .setReceivedTitleCallback(mCallback)
                .setSecurityType(AgentWeb.SecurityType.strict)
                .createAgentWeb()//
                .ready()//
                .go(getUrl());


        initView(view);
    }


    public WebSettings getSettings(){
        return WebDefaultSettingsManager.getInstance();
    }
    public String getUrl(){
        String target="";

        if(TextUtils.isEmpty(target=this.getArguments().getString(URL_KEY))){
            target="http://www.epfresh.com";
        }
//        target = "http://mtest.epfresh.com/purchase/red_packet.html?num=1706001&type=_share_&phone=13661871034&token=021de1a9537342cda6f48a456ccfa656&cid=00000000-04fa-30f8-0000-00005a3e0e69";
        return target;
    }
    protected ChromeClientCallbackManager.ReceivedTitleCallback mCallback=new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
//            if(mTitleTextView!=null&&!TextUtils.isEmpty(title))
//                if(title.length()>10)
//                    title=title.substring(0,10)+"...";
//                mTitleTextView.setText(title);

        }

    };

    protected WebViewClient mWebViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e("url",url);
            if (url != null && url.startsWith("epfreshbuyerclick://product")) {
                Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                String id = Uri.parse(url).getQueryParameter("id");
                int serviceStoreId = Integer.parseInt(Uri.parse(url).getQueryParameter("serviceStoreId"));
                intent.putExtra("storeId", Uri.parse(url).getQueryParameter("storeId"));
                intent.putExtra("id", id);
                intent.putExtra("serviceStoreId", serviceStoreId);
                startActivity(intent);
                return true;
            } else if (url != null && url.startsWith("epfreshbuyerclick://promotionproduct")) {
                Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                String id = Uri.parse(url).getQueryParameter("id");
                int serviceStoreId = Integer.parseInt(Uri.parse(url).getQueryParameter("serviceStoreId"));
                String promotionId = Uri.parse(url).getQueryParameter("promotionid");
                intent.putExtra("storeId", Uri.parse(url).getQueryParameter("storeId"));
                intent.putExtra("id", id);
                intent.putExtra("promotionItemId", promotionId);
                intent.putExtra("serviceStoreId", serviceStoreId);
                startActivity(intent);
                return true;
            } else if (url != null && url.startsWith("epfreshbuyerclick://store")) {
//                    SalesType=1整货,SalesType=2散货

                Intent tv_bulk_load = new Intent(getActivity(),
                        DcStoreActivity.class);
                tv_bulk_load.putExtra("data", getActivity().getIntent().getStringExtra("data"));
                startActivity(tv_bulk_load);
                return true;
            } else {
//                    view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            ptrFrameLayout.refreshComplete();
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            webView = view;
            Log.i("Info","url:"+url+"   target:"+getUrl());
            if(url.equals(getUrl())){
                pageNavigator(View.GONE);
            }else{
                pageNavigator(View.VISIBLE);
            }


        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        Log.i("Info","onActivityResult result");
        mAgentWeb.uploadFileResult(requestCode,resultCode,data);
    }

    protected void initView(View view) {
//        mBackImageView = (ImageView) view.findViewById(R.id.iv_back);
//        mLineView = view.findViewById(R.id.view_line);
//
//        mFinishImageView = (ImageView) view.findViewById(R.id.iv_finish);
//        mTitleTextView = (TextView) view.findViewById(R.id.toolbar_title);
//
//        mBackImageView.setOnClickListener(mOnClickListener);
//        mFinishImageView.setOnClickListener(mOnClickListener);

        pageNavigator(View.GONE);
    }

    private void pageNavigator(int tag) {

        Log.i("Info","TAG:"+tag);
//        mBackImageView.setVisibility(tag);
//        mLineView.setVisibility(tag);
    }

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            switch (v.getId()){

//                case R.id.iv_back:
//
//                    if(!mAgentWeb.back())
//                        StoreHomeWebFragment.this.getActivity().finish();
//
//                    break;
//                case R.id.iv_finish:
//                    StoreHomeWebFragment.this.getActivity().finish();
//                    break;
            }
        }
    };

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public boolean onFragmentKeyDown(int keyCode, KeyEvent event) {
        return mAgentWeb.handleKeyEvent(keyCode,event);
    }

    @Override
    public void onDestroyView() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        webView = null;
        super.onDestroyView();
        //  mAgentWeb.destroy();
    }
    private Handler mHandler = new Handler();
    String h5Key = "";
    public class JsBridge {
        @JavascriptInterface
        public void callHandler(String functionName, String value, final String param3) {
            Log.e("functionName:", functionName + "_____________________");
            Log.e("just begin","JsBridge"+"callHandler");
            h5Key = param3;
            if ("loginData".equals(functionName)) {//登录信息
                final Map map = new ArrayMap();
                map.put("clientIdentifierCode", AppUtils.getUniquePsuedoID());
                map.put("token", ApplicationHelper.getInstance().getUser().getAccess_token());
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("deviceInfo".equals(functionName)) {//设备信息
                final Map map = new ArrayMap();
                map.put("os", "android");
                map.put("osVersion", Build.VERSION.RELEASE);
                map.put("model", Build.MODEL);
                map.put("net", IntenetUtil.getNetworkState(getContext()));
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }
            if ("getStoreInfo".equals(functionName)) {//todo: 采购端哪儿来的店铺信息？？？
                final Map map = new ArrayMap();
/*                map.put("storeType", ApplicationHelper.getInstance().getMerchant().getStoreCategoryType());
                map.put("storeName", ApplicationHelper.getInstance().getStoreName());*/
                mHandler.post(new Runnable() {
                    public void run() {
                        evaluateJs("JSBridgeCallback('" + param3 + "'" + ",'" + new GsonBuilder().create().toJson(map) + "')");
                    }
                });
            }

            if ("appCallBack".equals(functionName)) {//返回结束
                getActivity().finish();
            }

            if ("commodityDetail".equals(functionName)) {//返回结束
                getActivity().finish();
            }

            if ("openLink".equals(functionName)) {//返回结束
                getActivity().finish();
            }

            if ("openList".equals(functionName)) {//返回结束
                getActivity().finish();
            }
        }
    }

    @TargetApi(10)
    void evaluateJs(final String value) {
        Log.e("just begin","evaluateJs"+"callHandler");
        Log.e("javascript",value.toString());
        final int version = Build.VERSION.SDK_INT;// 因为该方法在 Android 4.4 版本才可使用，所以使用时需进行版本判断
        if (version < 19) {
            webView.loadUrl(value);
        } else {
            webView.evaluateJavascript(value, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        }
    }

}
